package com.chenc.javathreads.TestJavaLock.synchronizecount;

import java.util.HashSet;

/**
 * @ClassName
 * @Describtion: 锁静态方法 用的少
 * @Author:Chenc
 * @Date:2023/11/23 16:49
 * @Version 1.0
 */
public class SynchronizedStaticMethod {
    //变量
    private static int number = 0;

    static class Counter{
        //循环次数
        private static int MAX_COUNT = 1000000;
        private static HashSet idset = new HashSet<>();
        private static HashSet nameset = new HashSet<>();

        //++方法
        public synchronized static void incr() {
            for (int i = 0; i < MAX_COUNT; i++) {
                number++;
                Thread thread = Thread.currentThread();
                idset.add(thread.getId());
                nameset.add(thread.getName());
            }
        }

        //--方法
        public synchronized static void decr() {
            for (int i = 0; i < MAX_COUNT; i++) {
                number--;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            Counter.incr();
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            Counter.decr();
        });
        t2.start();
        t1.join();
        t2.join();
        System.out.println(" 最终的结果：" + number);
        System.out.println(Counter.nameset);
        System.out.println(Counter.idset);

    }
}

